package com.laicunba.ext.web.controller.h5.activity;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.constant.GloabConstant;
import com.laicunba.ext.service.SlaveActivityJoinService;
import com.laicunba.ext.service.SlaveVcoinService;
import com.laicunba.ext.web.controller.SuiCunBaoBaseController;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.pojo.vo.WeiXinVO;
import com.laicunba.service.ActivityJoinService;
import com.laicunba.service.PicService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UserService;
import com.laicunba.service.VcoinWalletService;
import com.laicunba.service.WeiXinService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.QRcodeUtil;
import com.laicunba.util.StringUtil;
 
//@Controller
@RequestMapping(value = "/h5/ext/activity")
public class CelebrateDepositoryController extends SuiCunBaoBaseController {
	private static final Logger LOG = Logger.getLogger(CelebrateDepositoryController.class);
	@Autowired
	private RegistryService registryService;
	@Autowired
	private VcoinWalletService vcoinWalletService;
	@Autowired
	private SlaveVcoinService slaveVcoinService;
	@Autowired
	private SlaveActivityJoinService slaveActivityJoinService;
	@Autowired
	private WeiXinService weiXinService;
	@Autowired
	private PicService picService;
	@Value("${ftp.dir:/resource/}")
	private String ftpDir;
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/celebrate_online.htm")
	public ModelAndView celebrateDepository(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("celebrate-online.jsp");
		try {
			UserDO loginUser = getCurrentUser(request);
			if(loginUser != null) {
				//清理老活动的累积积分，如果已清理则不再次进行
				RegistryDO cleanInviteVcoinRegistry = registryService.get(RegistryDO.class, "u." + loginUser.getId() + ".clean-act20170703-vcoin");
				if(cleanInviteVcoinRegistry == null) {
					long balance = vcoinWalletService.getBalance(loginUser.getId());
					if(balance > 0) {
						vcoinWalletService.subtract(loginUser.getId(), (int) balance, "CELEBRATE_DEPOSITORY_CLEAN", "庆存管上线活动积分清零");
					}
					
					cleanInviteVcoinRegistry = new RegistryDO();
					cleanInviteVcoinRegistry.setId("u." + loginUser.getId() + ".clean-act20170703-vcoin");
					cleanInviteVcoinRegistry.setVal(String.valueOf(balance));
					cleanInviteVcoinRegistry.setVisible(true);
					cleanInviteVcoinRegistry.setSummary("庆存管上线活动清除老活动的累积积分");
					registryService.create(cleanInviteVcoinRegistry);
				}
				
				String regChanceKey = "act.20170703chance." + loginUser.getId() + ".regist";
				String cjCountKey = "act.20170703CJ." + loginUser.getId() + "." + DateUtil.formatDate(new Date());
				String chanceKey = "act.20170703chance." + loginUser.getId()+ "." + DateUtil.formatDate(new Date());
				int regChance = StringUtil.isNotEmpty(CacheUtil.getAttribute(regChanceKey)) ? Integer.parseInt(CacheUtil.getAttribute(regChanceKey)) : 0 ;
				int todayTotalChance = StringUtil.isNotEmpty(CacheUtil.getAttribute(chanceKey)) ? Integer.parseInt(CacheUtil.getAttribute(chanceKey)) : 0 ;
				int todayCjCount = StringUtil.isNotEmpty(CacheUtil.getAttribute(cjCountKey)) ? Integer.parseInt(CacheUtil.getAttribute(cjCountKey)) : 0 ;
				int shakeChance = 0;
				if(regChance > 0) {
					shakeChance += regChance;
				}
				if(todayTotalChance > 0 && todayCjCount >=0) {
					shakeChance += (todayTotalChance - todayCjCount);
				}
				long vcoinBalance = vcoinWalletService.getBalance(loginUser.getId());
				if(vcoinBalance > 0) {
					shakeChance += (vcoinBalance/300);
				}
				view.addObject("shakeChance", shakeChance);
				view.addObject("loginStatus", "1");
				view.addObject("vcoinBalance", vcoinBalance);
				
				
				String uri = request.getRequestURI();
				uri = uri.substring(request.getContextPath().length());
				String link = GloabConstant.WEB_PATH + uri;
				if(StringUtil.isNotEmpty(request.getQueryString())) {
					link += "?" + request.getQueryString();
				}
				if (StringUtil.isEmpty(loginUser.getInviteCode())) {
					// 生成邀请码
					loginUser.setInviteCode(getRandomString());
				}
				if (StringUtil.isEmpty(loginUser.getInviteQrCode()) && StringUtil.isNotEmpty(loginUser.getInviteCode())) {
					File qrcodeDir = new File(GloabConstant.PIC_ROOT + "/invite/");
					if (!qrcodeDir.exists()) {
						qrcodeDir.mkdirs();
					}
					File qrCodeFile = new File(qrcodeDir, loginUser.getId() + ".png");
					try {
						QRcodeUtil.make(GloabConstant.WEB_PATH + "/h5/regist_new.jsp?invite_code=" + loginUser.getInviteCode()
							+"&mobile="+loginUser.getMobile().toString().substring(0,3)+"****"+loginUser.getMobile().toString().substring(7), qrCodeFile, 300, 300);
						loginUser.setInviteQrCode("invite/" + loginUser.getId() + ".png");
						picService.upload2Ftp(new FileInputStream(qrCodeFile), ftpDir+"invite/" + loginUser.getId() + ".png");
						userService.updateSkipCheckOwner(loginUser);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				WeiXinVO weiXinVO = new WeiXinVO();
				weiXinVO.setLink(link);
				LOG.info(String.format("【20170704庆存管上线活动】url=[%s]", "u."+weiXinVO.getLink()));
				weiXinVO = weiXinService.getWeiXinVO(weiXinVO);
				LOG.info(String.format("【20170704庆存管上线活动】url=[%s]", "u."+weiXinVO.getLink()));
				view.addObject("weiXinVO",weiXinVO);
				view.addObject("inviteCode", loginUser.getInviteCode());
				view.addObject("mobile",loginUser.getMobile().toString().substring(0,3)+"****"+loginUser.getMobile().toString().substring(7));
				
			} else {
				view.addObject("loginStatus", "0");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/celebrate_depository_login_status.htm")
	public String celebrateDepositoryLoginStatus(HttpServletRequest request){
		JSONObject json = new JSONObject();
		UserDO user = getCurrentUser(request);
		if(user == null) {
			json.put("loginStatus", 0);
		} else {
			json.put("loginStatus", 1);
		}
		return json.toJSONString();
	}
	
	@RequestMapping(value = "/invest_bill.htm")
	public ModelAndView investBill(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("invest-bill.jsp");
		UserDO loginUser = getCurrentUser(request);
		if(loginUser == null) {
			return view;
		}
		
		view.addObject("vcoinList", slaveVcoinService.findVcoinList(loginUser.getId(), "CELEBRATE_DEPOSITORY_ONLINE", 100));
		return view;
	}
	
	@RequestMapping(value = "/convert_bill.htm")
	public ModelAndView convertBill(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("convert-bill.jsp");
		UserDO loginUser = getCurrentUser(request);
		if(loginUser == null) {
			return view;
		}
		view.addObject("myConvertList", slaveActivityJoinService.analysisUserReward("20170703", loginUser.getId()));
		return view;
	}
	
	@RequestMapping(value = "/shake_bill.htm")
	public ModelAndView shakeBill(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("shake-bill.jsp");
		UserDO loginUser = getCurrentUser(request);
		if(loginUser == null) {
			return view;
		}
		
		view.addObject("myShakeList", slaveActivityJoinService.analysisUserReward("20170703", loginUser.getId()));
		return view;
	}

	private String getRandomString() {
		String base = "0123456789";
		// 生成字符串从此序列中取
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		String inviteCode = sb.toString();
		List<UserDO> userDOList = userService.findListByInviteCode(inviteCode);
		if (userDOList != null && userDOList.size() > 0) {
			inviteCode = getRandomString();
		}
		return inviteCode;
	}
}
